//
//  MPMediaPickerController+RACSignal.m
//  高仿暴走斗图
//
//  Created by huangsongyao on 16/4/30.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "MPMediaPickerController+RACSignal.h"
#import "NSObject+RACDescription.h"

@implementation MPMediaPickerController (RACSignal)

static void RACUseDelegateProxy(MPMediaPickerController *self) {
    
    if (self.delegate == (id)self.rac_delegateProxy) return;
    self.rac_delegateProxy.rac_proxiedDelegate = self.delegate;
    self.delegate = (id)self.rac_delegateProxy;
}

- (RACDelegateProxy *)rac_delegateProxy {
    
    RACDelegateProxy *proxy = objc_getAssociatedObject(self, _cmd);
    if (proxy == nil) {
        proxy = [[RACDelegateProxy alloc] initWithProtocol:@protocol(MPMediaPickerControllerDelegate)];
        objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    return proxy;
}

- (RACSignal *)rac_mediaSelectSignal {
    
    RACSignal *pickerCancelledSignal = [[self.rac_delegateProxy
                                         signalForSelector:@selector(mediaPickerDidCancel:)]
                                        merge:self.rac_willDeallocSignal];
    
    RACSignal *imagePickerSignal = [[[[self.rac_delegateProxy
                                       signalForSelector:@selector(mediaPicker:didPickMediaItems:)]
                                      reduceEach:^(MPMediaPickerController *mediaPicker, MPMediaItemCollection *mediaItemCollection) {
                                          
                                          return mediaItemCollection;
                                      }]
                                     takeUntil:pickerCancelledSignal]
                                    setNameWithFormat:@"%@ -rac_imageSelectedSignal", self.rac_description];
    
    RACUseDelegateProxy(self);
    
    return imagePickerSignal;
}

@end
